﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using BEPUphysics.Entities;

namespace Asplode
{
    public class GameObject : DrawableGameComponent
    {
        public enum Type { NO_TYPE, PLAYER, PROJECTILE };

        // The physics entity representing this object.
        public Entity body;

        // The graphical representation of the object.
        public Model model;

        // Graphical transforms.
        protected Matrix transform;
        protected Matrix[] boneTransforms;

        public bool isFiring;
        public float rotation;

        public GameObject(Entity entity, Model model, Matrix transform, Game game)
            : base(game)
        {
            this.body = entity;
            this.model = model;
            this.transform = transform;
            isFiring = false;

            //Collect any bone transformations in the model itself.
            //The default cube model doesn't have any, but this allows the EntityModel to work with more complicated shapes.
            boneTransforms = new Matrix[model.Bones.Count];
            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.EnableDefaultLighting();
                    effect.DiffuseColor = Color.Gray.ToVector3();
                }
            }
        }

        public override void Draw(GameTime gameTime)
        {
            //Notice that the entity's worldTransform property is being accessed here.
            //This property is returns a rigid transformation representing the orientation
            //and translation of the entity combined.
            //There are a variety of properties available in the entity, try looking around
            //in the list to familiarize yourself with it.
            Matrix worldMatrix = transform * body.worldTransform;

            model.CopyAbsoluteBoneTransformsTo(boneTransforms);
            Game game = Game as Game;
            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.World = boneTransforms[mesh.ParentBone.Index] * worldMatrix;
                    effect.View = Matrix.CreateLookAt(game.Map.CameraPosition, Vector3.Zero, Vector3.Up);
                    effect.Projection = game.Map.CameraProjection;
                }
                mesh.Draw();
            }
        }
    }
}
